<script setup>
import { ref,reactive, nextTick,onActivated,getCurrentInstance,onMounted, watch  } from 'vue'; 
import { useRoute,useRouter } from 'vue-router';
import { arrowMiddleware, ElMessage,ElMessageBox  } from 'element-plus';
import ExtansionDailog from './components/ExtansionDailog.vue';
import QcodeVue from './components/Qrcode.vue';
import { downloadQRCode,removeReferences,extensionManagementList,referrerStatusEdit } from '@/api/ExtensionManage'
const seachTable = ref(null);
const route = useRoute();
const router = useRouter();
const instance = getCurrentInstance();
const miniAppId = import.meta.env.VITE_APP_WEIXINID;
// 弹框组件代码

const dialogVisible = ref(false)
const dialogTitle = ref('')

const changeDialog = (val) => {
    dialogVisible.value = val
}

const successSubmit = (val) => {
   dialogVisible.value = false
   if(val == 'add'){
     seachTable.value.initSearch();
   }else{
     seachTable.value.handlerSearch();
   }
   instance.proxy.$forceUpdate();
}


let backForm = ref({
    referrerName:'', //姓名
    referrerPhone:'', //手机号
    id:''
})

// 二维码弹框组件
const dialogQcodeVisible = ref(false)
const dialogQcodeTitle = ref('')
const QcodeContent = ref('')
const size = ref(162)
const QcodeName = ref('')
const changeQcodeDialog = (val) => {
    dialogQcodeVisible.value = val
}
const ContentImg = ref('')


// 状态值改变
// 启用禁用switch选择
const changeStatue = (val,row) => {
  // console.log(val,'val');
  // console.log(row,'row');
  ElMessageBox({
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          title: val ? '启用' : '禁用',
          showCancelButton: true,
          message:val ? "确定要启用吗?" : "确定要禁用吗",
          beforeClose: async (action, instance, done) => {
              if (action === 'confirm') {
                  instance.confirmButtonLoading = true
                  instance.confirmButtonText = 'Loading...'
                  try {
                    let data = {
                      referrerId: row.id,
                      referrerStatus:val
                    }
                     const res = await referrerStatusEdit(data)
                     console.log(res,'res');
                     val ? ElMessage.success('启用成功') : ElMessage.success('禁用成功')
                      // ElMessage.success('禁用成功');
                     
                  } catch (error) {
                    
                  }finally{
                    seachTable.value.handlerSearch();
                    instance.confirmButtonLoading = false
                    done()
                  }
                 
                
              } else {
                  seachTable.value.handlerSearch();
                  done()
              }
          },
      })
}

// 新增编辑回退时候刷新列表 
// onActivated(()=>{

//     let closeTagName = sessionStorage.getItem('closeTagName');
//     if(closeTagName == 'pharmacistManageEdit'){
//         seachTable.value.handlerSearch();
        
//     }else if(closeTagName == 'pharmacistManageAdd'){
//         seachTable.value.initSearch();
//     }
//     instance.proxy.$forceUpdate();
//     sessionStorage.removeItem('closeTagName');
// })
const formInline = ref([
    {
      type: "input",
      prop: "queryCondition",
      placeholder: "推广人姓名或手机号",
      label: "",
      model: "",
    },
    {
        type: "select",
        placeholder: "状态",
        label: '',
        prop: 'referrerStatus',
        data:[
            {
                label:"启用",
                value:1
            },
            {
                label:"禁用",
                value:0
            }
        ],
        model: [],
    }
])

const btnLefts = ref([
    {
        label:"新增",
        plain:false,
        type:"primary",
        show:true,
        img:new URL("@/assets/icon/btn-add.png",import.meta.url),
        click:async ()=>{
          backForm.value = {
              referrerName:'', //姓名
              referrerPhone:'', //手机号
              id:''
          }

            dialogTitle.value = '新增推广人员'
            dialogVisible.value = true
        }
    },

])
const btnRights = ref([
    // {
    //     label:"导出",
    //     plain:false,
    //     plain:true,
    //     show:true,
    //     img:new URL("@/assets/icon/btn-export.png",import.meta.url),
    //     style:"border-color:#0C268C;color:#0C268C",
    //     click:async ()=>{

    //     }
    // }
])

const tableConfig = ref([
    {
      prop: "referrerName",
      label: "姓名",

    },
    {
      prop: "referrerPhone",
      label: "手机号码",
   
    },

    {
      type:'slot',
      prop: "type",
      label: "状态",
      slotName:'statusName'
    },
    {
      prop: "createTime",
      label: "创建时间",
   
    },
    {
      type: "action",
      label: "操作",
      width: 450,
      btns: [
        {
          label: () => "下载二维码",
          show:(row)=>{
            return true;
          },
          click: async (row) => {

            try {
              tableLoading.value = true;
              let data = {
                scene:`type=${3}&rId=${row.id}`,
                page:'pages/index/index',
                referrerId:row.id,
                miniAppId
              } 
              const res = await downloadQRCode(data)
              console.log(res,'res');


              dialogQcodeTitle.value = '二维码'
              QcodeContent.value = res.url || ''
              QcodeName.value = res.referrerName || ''
              dialogQcodeVisible.value = true
            } catch (error) {
            
            }finally{
              tableLoading.value = false;
            }

          
            // ContentImg.value = 'https://static.91medicine.net/pharmacymini/images/xiaojiu.png' 
            // router.push({name:"pharmacistManageDetail",query:{uuid:row.uuid}})
          },
        },
        {
          label: () => "详情",
          
          click: async (row) => {
            router.push({name:"ExtensionPerManageDetail",query:{id:row.id, referrerName:row.referrerName}})
          },
        },
        {
          label: () => "编辑",
          type:"success",
          show:(row)=>{
            return true;
          },
          click: async (row) => {
            dialogTitle.value = '编辑推广人员'
            dialogVisible.value = true
            backForm.value = {
              referrerPhone:row.referrerPhone,
              referrerName:row.referrerName,
              id:row.id
            }
            // instance.proxy.$forceUpdate()
            console.log(backForm.value,'backForm.value');
        
          },
        },
     
        {
          label: () => "删除",
          type:"danger",
          show:(row)=>{
            return true;
          },
          click: async (row) => {
            ElMessageBox(
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'error',
                    title: '提示',
                    showCancelButton: true,
                    confirmButtonClass: 'delete',
                    message:`确定删除推广人【${row.referrerName}】?`,
                    beforeClose: async (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true
                            instance.confirmButtonText = 'Loading...'
                            try {
                              const res = await removeReferences(row.id)
                              ElMessage.success('删除成功');
                             
                            } catch (error) {
                              
                            }finally{
                              seachTable.value.handlerSearch();
                              instance.confirmButtonLoading = false
                              done()
                            }
                          
                        } else {
                            done()
                        }
                    },
                }
            )
          },
        },
      ],
    },
]);
const tableLoading = ref(false)
const totalPage = ref(0)
const tableData = ref([]);


const handlerSearch = async (formInline)=>{
    tableLoading.value = true;
    try{
      let data = {
          ...formInline,
          
        }
        const res = await extensionManagementList(data)
        console.log(res,'res');
        totalPage.value = Number(res.total);
        tableData.value =  res.records || []
        tableLoading.value = false;
    }catch(e){
        tableLoading.value = false;
    }
}



</script>
<template>
    <div class="page-content">
        <SeachTable 
          :tableType="1"
          ref="seachTable"
          :forms="formInline"
          :btnLefts="btnLefts"
          :btnRights="btnRights"
          :tableLoading="tableLoading"
          :tableConfig="tableConfig"
          :tableData="tableData"
          :totalPage="totalPage"
          :tableIndex="true"
          @handlerSearch="handlerSearch"
        >
        <template #statusName="{row, index}">
          <el-switch v-model="row.referrerStatus"  @change="(val) => changeStatue(val,row)"/>
        </template>
        </SeachTable>
        <extansion-dailog
        v-if="dialogVisible"
        :dialogVisible="dialogVisible"
        :dialogTitle="dialogTitle"
        :backForm="backForm"
        @changeDialog="changeDialog" 
        @successSubmit="successSubmit"
        ></extansion-dailog>
        <qcode-vue
        v-if="dialogQcodeVisible"
        :dialogQcodeVisible="dialogQcodeVisible"
        :dialogQcodeTitle="dialogQcodeTitle"
        :QcodeContent="QcodeContent"
        :size="size"
        :QcodeName="QcodeName"
        :ContentImg="ContentImg"
        @changeQcodeDialog="changeQcodeDialog"
        ></qcode-vue>
    </div>
</template>


<!-- 删除按钮样式 -->
<style lang="less">
.delete{
    background: #FF2440 !important;
}
</style>